package memberrank

import (
	"context"
	"encoding/json"
	"strings"

	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/common/enum/errorcode"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/setting/rpc/settingclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateMemberRankLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCreateMemberRankLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateMemberRankLogic {
	return &CreateMemberRankLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CreateMemberRankLogic) CreateMemberRank(req *types.CreateMemberRankReq) (resp *types.BaseMsgResp, err error) {
	if req.Name == nil || len(strings.TrimSpace(*req.Name)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "setting.memberRankNameRequired"))
	}
	if req.Code == nil || len(strings.TrimSpace(*req.Code)) == 0 {
		return nil, errorx.NewCodeError(errorcode.InvalidArgument,
			l.svcCtx.Trans.Trans(l.ctx, "setting.memberRankCodeRequired"))
	}

	var restrictions []*settingclient.MemberRankRestrictionInfo
	if len(req.Restrictions) > 0 {
		for _, v := range req.Restrictions {
			restrictions = append(restrictions, &settingclient.MemberRankRestrictionInfo{
				TaskId:    v.TaskId,
				Threshold: v.Threshold,
				Sort:      v.Sort,
			})
		}
	}

	var rules []*settingclient.MemberRankRuleInfo
	if len(req.Rules) > 0 {
		for _, v := range req.Rules {
			regions, err := json.Marshal(v.Regions)
			if err != nil {
				logx.Errorw("CreateMemberRank MemberRankRuleInfo json.Marshal err", logx.Field("detail", err.Error()))
				continue
			}

			rules = append(rules, &settingclient.MemberRankRuleInfo{
				RuleType:   v.RuleType,
				Regions:    pointy.GetPointer(string(regions)),
				Mode:       v.Mode,
				Value:      v.Value,
				PeriodType: v.PeriodType,
				Quota:      v.Quota,
				Sort:       v.Sort,
			})
		}
	}

	res, err := l.svcCtx.SettingRpc.BackendCreateMemberRank(l.ctx, &settingclient.MemberRankInfo{
		Name:           req.Name,
		Code:           req.Code,
		Description:    req.Description,
		Remark:         req.Remark,
		PicId:          req.PicId,
		PicUrl:         req.PicUrl,
		PointThreshold: req.PointThreshold,
		IsDefault:      req.IsDefault,
		Sort:           req.Sort,
		Status:         req.Status,
		Restrictions:   restrictions,
		Rules:          rules,
	})
	if err != nil {
		return
	}

	return &types.BaseMsgResp{
		Success: true,
		Msg:     l.svcCtx.Trans.Trans(l.ctx, res.Msg),
	}, nil
}
